﻿<%@ page language="java" contentType="text/html; charset=UTF-8"  
import="java.util.*,java.text.SimpleDateFormat,
com.brother.model.*,com.ibatis.common.util.PaginatedList,com.brother.util.MyPaginatedList
,com.brother.util.DateFormatter,com.brother.model.AlarmType,com.brother.*,com.brother.service.*"  pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ include file="international.jsp" %> 
<jsp:useBean id="trackerService" class="com.brother.service.TrackerService"></jsp:useBean>
<jsp:useBean id="report" class="com.brother.model.Report"></jsp:useBean>
<jsp:useBean id="reportService" class="com.brother.service.ReportService"></jsp:useBean>
<jsp:setProperty property="*" name="report"/>
<% 
com.brother.model.Customer user = (com.brother.model.Customer)session.getAttribute(com.brother.Constants.LOGIN_SESSTION_NAME);
if(user == null){
	return;
}
String sessesionLocal = (String)session.getAttribute("locale");
String fromDate = request.getParameter("fromDate");
String toDate = request.getParameter("toDate");
System.out.println(" state:"+report.getState()+"trackerid:"+report.getTrackerid()+" param:"+request.getParameter("tracker.trackerid"));
List<Tracker> trackers = trackerService.findUserTracker(user.getUserid());

report.setUserId(user.getUserid());	
report.setOrderCondition("order by createtime asc");
String pageNo = request.getParameter("pageNo");
String action = request.getParameter("action");
String startTime = request.getParameter("startTime");
String endTime = request.getParameter("endTime");
if(pageNo == null || !pageNo.matches("^\\d*$")){
	pageNo = "0";
}

String dateFormat = (String)session.getAttribute(Constants.DATE_FORMAT_SESSION_NAME);
SimpleDateFormat formatEn = new SimpleDateFormat("dd/MM/yyyy HH:mm"); // English date format
SimpleDateFormat formatPT = new SimpleDateFormat("dd/MM/yyyy HH:mm"); // Portul date format

SimpleDateFormat sessionFormat = new SimpleDateFormat(dateFormat + " HH:mm");

SimpleDateFormat formatCN = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // 


String extDateFormat = (String)session.getAttribute(Constants.EXT_DATE_FORMAT_SESSION_NAME);

DateFormatter localFormat = new DateFormatter(); 
localFormat.setConfig(user.getTimeZoneOffSet(), dateFormat+" HH:mm:ss");


if(action == null){
	report.setPageSize(50);
	Calendar calendar = Calendar.getInstance();
	calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 7);
	report.setCreateTimeFrom(formatCN.format(calendar.getTime()));
	report.setCreateTimeTo(formatCN.format(new Date())+" "+endTime);
	report.setTrackerid("00000000");
	session.setAttribute("searchRealTimeData",report);
} else if(action.equalsIgnoreCase("search")) {
	report.setCreateTimeFrom(fromDate+" "+startTime);
	report.setCreateTimeTo(toDate+" "+endTime);
	if(!DateFormatter.isChineaseFormat(report.getCreateTimeFrom())){
		report.setCreateTimeFrom(formatCN.format(sessionFormat.parse(report.getCreateTimeFrom())));
		report.setCreateTimeTo(formatCN.format(sessionFormat.parse(report.getCreateTimeTo())));
	}
	
	report.setCreateTimeFrom(DateFormatter.toEastEight(formatCN.parse(report.getCreateTimeFrom()), user.getTimeZoneOffSet(), "yyyy-MM-dd HH:mm"));
	report.setCreateTimeTo(DateFormatter.toEastEight(formatCN.parse(report.getCreateTimeTo()), user.getTimeZoneOffSet(), "yyyy-MM-dd HH:mm"));
	session.setAttribute("searchRealTimeData",report);
}else if(action.equalsIgnoreCase("page")){
	report = (Report)session.getAttribute("searchRealTimeData"); 
}


report.setUserId(user.getUserid());

DateFormatter format = new DateFormatter();  
format.setConfig(user.getTimeZoneOffSet(), dateFormat+" HH:mm:ss");
report.setLanguage((String)session.getAttribute("locale")); 
PaginatedList pageData = reportService.findData(pageNo, report.getPageSize(),report);
//System.out.println("from time="+report.getCreateTimeFrom()+" to time="+report.getCreateTimeTo()+" state="+report.getState()+" size="+pageData.size());
int totalSize = ((MyPaginatedList)pageData).getTotalSize();//reportService.findDataSize(report.getPageSize(),report);
int totalPages = totalSize / report.getPageSize() + 1;





String distance = request.getParameter("distance");
if(distance == null){
	distance = "0";
}
String previousPageFirstDistance = request.getParameter("previousPageFirstDistance");
if(previousPageFirstDistance == null){
	previousPageFirstDistance = "0";
}
%>	
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title><fmt:message key="report.title"/> - <fmt:message key="company.name"/></title>
<meta name="description" content="<fmt:message key="description.keyword"/>" />
<link rel="stylesheet" type="text/css" media="all" href="style.css" />

<link rel="stylesheet" type="text/css" href="css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="css/grid-examples.css" />
<style type=text/css>
        /* style rows on mouseover */
        .x-grid3-row-over .x-grid3-cell-inner {
            font-weight: bold;
        }
        .x-grid3{
        	height:100%;
        }
        .x-grid3-viewport{
        	height:100%;
        }
        .x-grid3-scroller{
        	overflow:auto;
			position:relative;
			height:100%;
        }
        .x-grid3-cell-inner{
         	text-align:left;
        }
        .x-grid3-hd-inner{
        	text-align:left;
        }
        body{
        background-color:#FFFFFF;
        }
    </style>
    
    
    <script type="text/javascript" src="js/ext-base.js"></script>
    <script type="text/javascript" src="js/ext-all.js"></script>
<script type="text/javascript" src="js/TableGrid.js"></script>
<script type="text/javascript" src="js/reportUpdateAddress.js?version=4"></script>
<script type="text/javascript" src="../js/common.js"></script>

</head>
<body>
<div id="msg" name="msg" style="background-color:#D4DF55; position:absolute; z-index:11; left: 10px; top: 61px; display:inline"></div>
<script>
var waitingMsg = '<fmt:message key="waiting.msg"/>';
var waitingProgressText = '<fmt:message key="waiting.loading"/>';
var prevColor = "";
       function Point(iX, iY){ 
          this.x = iX; 
          this.y = iY; 
       } 
 function fGetXY(obj){ 
           var oTmp = obj;     
           if(!oTmp||(typeof(oTmp.offsetLeft) == "undefined") 
               ||(typeof(oTmp.offsetTop) == "undefined") 
               ||!oTmp.tagName){ 
                return null; 
           } 
           var pt = new Point(0,0);   
           do{ 
      pt.x += oTmp.offsetLeft; 
      pt.y += oTmp.offsetTop; 
      //alert(oTmp.parentNode.tagName);
      oTmp = oTmp.parentNode; 
  } while(oTmp.tagName!="BODY"); 
  return pt; 
       } 
       
	   var gMsgTop = 0; //fGetXY(document.getElementById("tmp_pos")).y;
function show_tip(msg)
{
	if (gMsgTop == 0)
	{
		gMsgTop = fGetXY(document.getElementById("tmp_pos")).y + 5;
		document.getElementById("msg").style.top = gMsgTop;
		document.getElementById("msg").style.display = "inline";
		// alert(document.getElementById("msg").style.offsetTop);
	}
	
	document.getElementById("msg").innerHTML = msg;
}
</script>

<script type="text/javascript" src="common.js"></script> 
<script charset="utf-8" src="http://maps.google.com/maps/api/js?sensor=false&language=<%=session.getAttribute("locale").toString().equals("zh")?"zh_CN":session.getAttribute("locale").toString()%>" type="text/javascript"></script>
	<script src="openLayers/OpenLayers.js" type="text/javascript"></script>
	<script src="openLayers/extention.js" type="text/javascript"></script>
<script type="text/javascript" src="js/google_map.js"></script> <script>

var trackerUserid = '<%=user.getUserid()%>';	
var locale = '<%=(String)session.getAttribute("locale")%>';

var time_zone = 8;
var g_default_time_zone_hours = parseInt(time_zone);
var g_default_time_zone_minutes = (time_zone - parseInt(time_zone)) * 60;

var g_str_comment = "";
var g_str_id = "ID:";
var g_str_lat = "Lat:";
var g_str_lng = "Lng:";
var g_str_signal = "Signal:";
var g_str_speed = "Speed:";
var g_str_state = "State:";

function get_gps_cmd_str(cmd)
{
	if (cmd == 0)
	{
		return "<fmt:message key="alarm.gps.pos"/>";
	}
	else if (cmd == "1")
	{
		return "<fmt:message key="alarm.input1"/>";
	}
	else if (cmd == "2")
	{
		return "<fmt:message key="alarm.input2"/>";
	}
	else if (cmd == "3")
	{
		return "<fmt:message key="alarm.input3"/>";
	}
	else if (cmd == "4")
	{
		return "<fmt:message key="alarm.gps.over.speed"/>";
	}
	else if (cmd == "5")
	{
		return "<fmt:message key="alarm.gps.geo.fence"/>";
	}
	else if (cmd == "6")
	{
		return "<fmt:message key="alarm.power.lost"/>";
	}
	else if (cmd == "7")
	{
		return "<fmt:message key="alarm.low.power"/>";
	}else if (cmd == "8")
	{
		return "<fmt:message key="alarm.sos"/>";
	}
	
	return "<fmt:message key="alarm.unknown"/>";
}



var win = null;



var gridPageSize = 14;
 var gridHeight  = 420;

trackerHeader = '<fmt:message key="grid.trackerHeader"/>';

Ext.onReady(function(){

	// create the grid
    Ext.get("plain-table").setStyle('display','');
    
    var grid = new Ext.ux.grid.TableGrid("plain-table", {
        stripeRows: true, // stripe alternate rows
        enableHdMenu:false,
        width:'auto',
        height:'auto'
    });

    grid.render();
    
    function getEmptyAddress(){
        if(!grid.rendered){
    		setTimeout(getEmptyAddress, 500);
    		return;
        }
        beginToAdd();
    }
    getEmptyAddress();
	
});

</script>
<script type="text/javascript"  src="js/gps.js"></script>
<script type="text/javascript" src="js/calendar.js"></script>
<script type="text/javascript" src="js/submodal.js"></script>


<script type="text/javascript">

function reLoadPage(shouldRefresh)
{	
}
var distance = <%=distance%>;
</script>

	
					<table id="plain-table" style="dispay:none"  cellpadding="3" cellspacing="0">
		<thead>		
	<tr>
		<th width="130"><strong><fmt:message key="report.date"/>:</strong></th>

		<th width="80"><strong><fmt:message key="location.lat"/>:</strong></th>
		<th width="80"><strong><fmt:message key="location.lng"/>:</strong></th>
		<th width="60"><strong><fmt:message key="report.speed"/>:</strong></th>
		

		 
		<th width="110"><strong><fmt:message key="report.alarm"/>:</strong></th>

		<th width="80"><strong><fmt:message key="report.distance"/>:</strong></th>
		<th width="200"><strong><fmt:message key="report.address"/>:</strong></th>
	</tr>
</thead>	



<%
Iterator<Report> datas = pageData.iterator();
float[] toPos = new float[2];
String lat = request.getParameter("lat");
String lng = request.getParameter("lng");

if(lat != null){
	try{
		toPos[0] = Float.parseFloat(lat);
		toPos[1] = Float.parseFloat(lng);
	}catch(Exception e){}
}
int row = 0;
while(datas.hasNext()){
	Report data = datas.next();
	if(row == 0 && pageNo.equals("0")){
		toPos[0] = data.getSignedLat();
		toPos[1] = data.getSignedLng();
	}
	
    SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
	Date Creatdate =dateFormat2.parse(localFormat.format(data.getCreateTime()));
	Creatdate.setHours(Creatdate.getHours()-13);
	
%>
		<tr style="cursor:default; color:<%if(data.getSignal().equalsIgnoreCase("ok")){%>#000000;<%}else{%>#A0A0A4;<%}%>" 
			onMouseOver="javascript:this.style.background='#4594dd'; prevColor = this.style.color; this.style.color='#ffffff';" onMouseOut="javascript:this.style.background='#ffffff'; this.style.color=prevColor;">
			<td style=" font-size:11px;"><b><%=Creatdate %></b></td>
			<td style=" font-size:11px;"><%=data.getSignedLat()%></td>
			<td style=" font-size:11px;"><%=data.getSignedLng()%></td>
			<td style=" font-size:11px;"><%=data.getSpeed()%></td>

			<td style=" font-size:11px;"><%=AlarmTypeService.getAlarmType(data.getState(), sessesionLocal)%></td>
			<td style=" font-size:11px;">
			<%if(report.getTrackerid() != null && report.getTrackerid().length() > 0){ %>
			<script>var from_pos = new GPS_LatLng(<%=data.getSignedLat()%>, <%=data.getSignedLng()%>);var to_pos = new GPS_LatLng(<%=toPos[0]%>, <%=toPos[1]%>);distance += from_pos.distanceFrom(to_pos);document.write(distance.toFixed(2) +" KM");</script>
			<%}else{ %>
			0 KM
			<%} %>
			</td>
			<td style=" font-size:11px;" width="280px" ><span id="address_<%=data.getReportId()%>"></span><%if(data.getAddress() == null){%> 
			
			<script>addAddress(<%=data.getSignedLat()%>, <%=data.getSignedLng()%>,'<%=data.getReportId()%>','<%=data.getTrackerid()%>');</script>
			 <%}else{%><%=data.getAddress()%><%} %></td>
		</tr>

<%
row +=1;
toPos[0] = data.getSignedLat();
toPos[1] = data.getSignedLng();
} %>	

		</table>
		
		
		
				<table width="100%" >
				<tr>
					<td align="center"   style="padding:5px; padding-right:30px; font-size:11px;">
					<div id="page_b" name="page_b" style="font-size:12px;width:100%;">
													
					<fmt:message key="report.number.pages"/> <%=pageData.getPageIndex()+1%> / <%=totalPages%>&nbsp;&nbsp;&nbsp;&nbsp;

					<%if(pageData.isFirstPage()){%><fmt:message key="report.previous"/><%}else {
							//pageData.previousPage();
							%>
					<a href="gps_report.jsp?action=page&pageNo=<%=pageData.getPageIndex()-1%>&lat=<%=((Report)pageData.get(0)).getSignedLat()%>&lng=<%=((Report)pageData.get(0)).getSignedLng()%>&distance=<%=previousPageFirstDistance%>"><fmt:message key="report.previous"/></a>
					<% //pageData.nextPage();
					} %>&nbsp;&nbsp;<%if(pageData.isLastPage()){ %><fmt:message key="report.next"/><%}else{%>
					<a id="nextPage" href="gps_report.jsp?action=page&pageNo=<%=pageData.getPageIndex()+1%>&lat=<%=toPos[0]%>&lng=<%=toPos[1]%>&previousPageFirstDistance=<%=distance%>"><fmt:message key="report.next"/></a>
					<%} %>
					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
					<a href="#noaction" onclick="location.href='report_export.jsp?updatetime='+(new Date()).getTime()"><fmt:message key="report.export.excel"/></a>
					
					</div>
					<script>
						var nextPage = document.getElementById("nextPage");	
						if(nextPage != null){
							nextPage.href = nextPage.href + "&distance="+distance.toFixed(2);
						}
						
					</script>
					
					</td>
				</tr>
								
			</table>







</body>
</html>
<%
com.brother.database.DataBase.closeThreadConnection();
%>